package ling.learn.antlr.cobol85;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.apache.commons.io.FileUtils;
import ling.learn.antlr.cobol85.parser.gen.Cobol85Lexer;
import ling.learn.antlr.cobol85.parser.gen.Cobol85Parser;
import ling.learn.antlr.cobol85.preprocessor.CobolPreprocessor;
import ling.learn.antlr.cobol85.preprocessor.CobolPreprocessor.CobolSourceFormatEnum;
import ling.learn.antlr.cobol85.preprocessor.impl.CobolPreprocessorImpl;
import ling.learn.antlr.common.AstDumper;

public class CobolAnalyzer {

  public void execute(String resourcePath, List<File> copyFiles) throws IOException {

    System.out.println(resourcePath);
    System.out.println("start preprocessor");
    CobolPreprocessor preprocessor = new CobolPreprocessorImpl();
    String lines =
        preprocessor.process(new File(resourcePath), copyFiles, CobolSourceFormatEnum.FIXED);

    System.out.println("output expend file");
    FileUtils.write(new File(resourcePath + ".expend"), lines, Charset.forName("MS932"));

    System.out.println("start parser");
    ParseTree tree = parser(lines);

    System.out.println("output AST file");
    dump(resourcePath + ".ast", tree);
  }

  private ParseTree parser(String lines) throws IOException {
    CharStream input = CharStreams.fromString(lines);
    Cobol85Lexer lexer = new Cobol85Lexer(input);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    Cobol85Parser parser = new Cobol85Parser(tokens);
    ParseTree tree = parser.startRule();
    return tree;
  }

  private void dump(String viewPath, ParseTree tree) throws IOException {
    AstDumper view = new AstDumper();
    view.dump(viewPath, tree, Cobol85Parser.VOCABULARY, false);
  }

}
